//
//  KABExhibitionVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/1/25.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABExhibitionVC.h"
#import "KABExhibitionTCell.h"
#import "ApiManager.h"
#import "XDAFNetworking.h"
#import "MBProgressHUD+XDPrompt.h"
#import <MJRefresh.h>
#import "KABModel.h"
#import "GlobalHeader.h"
#import "KABExhBuyVC.h"
#import "UIButton+EdgeInsets.h"
#import "KABExhDetailVC.h"
#import "XDSelectCityTVC.h"
#import "XDPickerDateView.h"
#import "NSDate+XDTimerFormatter.h"
#import <UIScrollView+EmptyDataSet.h>
#import "KABExhSearchVC.h"

@interface KABExhibitionVC ()<UITableViewDelegate, UITableViewDataSource, KABExhibitionTCellDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (weak, nonatomic) IBOutlet UIButton *cityBtn;
@property (weak, nonatomic) IBOutlet UIButton *timeBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (nonatomic, copy)   NSString *selCity;    // 为空或者@"全部"，表明是全部地区
@property (nonatomic, strong) NSDate *selDate;      // 为空，表明是全部时间
@property (nonatomic, readonly) KABExhibitionModel *exhModel;
@end

static NSString *const kReuseCellId = @"KABExhibitionTCell";
static NSInteger const kRequestExhibitionListSize = 15;

@implementation KABExhibitionVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"展会";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"cosplay_search"] style:UIBarButtonItemStylePlain target:self action:@selector(searchBarBtnTapped:)];
}

- (void)initSubViews {
//    [self.cityBtn layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageRight imageTitlespace:8.0];
//    [self.timeBtn layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageRight imageTitlespace:8.0];
//    [self refreshTitleBtn];
    
    [self.cityBtn addTarget:self action:@selector(cityBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.timeBtn addTarget:self action:@selector(timeBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 49.0, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 49.0, 0);
    
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 228.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
    // 刷新Btn
    [self refreshTitleBtn];
    
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有相关漫展喔" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.exhModel.exhibition_list.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABExhibitionTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.section < self.exhModel.exhibition_list.count) {
        [cell configViewWithExhListItem:self.exhModel.exhibition_list[indexPath.section]];
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    KABExhDetailVC *vc = [[KABExhDetailVC alloc] init];
    vc.exhItem = self.exhModel.exhibition_list[indexPath.section];
    [self showViewController:vc sender:nil];
}

#pragma mark - KABExhibitionTCellDelegate
- (void)kABExhibitionTCell:(KABExhibitionTCell *)cell imgViewTapped:(UIImageView *)imgView {
    ;
}
- (void)kABExhibitionTCell:(KABExhibitionTCell *)cell buyBtnTapped:(UIButton *)btn {
//    KABExhBuyVC *vc = [[KABExhBuyVC alloc] init];
//    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
//    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - event response
- (void)searchBarBtnTapped:(UIBarButtonItem *)item {
    KABExhSearchVC *exhSearchVC = [[KABExhSearchVC alloc] init];
    exhSearchVC.completeHandle = ^(NSInteger exhId) {
        [self jumpToExhDetailWithExhId:exhId];
    };
    [self presentViewController:exhSearchVC animated:YES completion:nil];
}

- (void)cityBtnTapped:(UIButton *)btn {
    XDSelectCityTVC *tvc = [[XDSelectCityTVC alloc] init];
    tvc.selectCity = ^(NSString *city) {
        self.selCity = city;
        [self refreshTitleBtn];
        [self.tableView.mj_header beginRefreshing];
    };
    [self showViewController:tvc sender:nil];
}

- (void)timeBtnTapped:(UIButton *)btn {
    XDPickerDateView *pickerDateView = [[XDPickerDateView alloc] initWithSelDate:self.selDate];
    pickerDateView.pickerDateHandle = ^(NSDate *date){
        self.selDate = date;
        [self refreshTitleBtn];
        [self.tableView.mj_header beginRefreshing];
    };
    [pickerDateView showInView:btn];
}

#pragma mark - private methods
- (void)jumpToExhDetailWithExhId:(NSInteger)exhId {
    KABExhDetailVC *vc = [[KABExhDetailVC alloc] init];
    vc.exhibition_id = exhId;
    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.exhModel.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    
    [self.tableView reloadData];
}

- (void)refreshTitleBtn {
    NSString *cityStr = self.selCity ? self.selCity : @"全部";
    [self.cityBtn setTitle:cityStr forState:UIControlStateNormal];
    [self.cityBtn layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageRight imageTitlespace:8.0];
    
    NSString *dateStr = @"时间";
    if (self.selDate) {
        dateStr = [NSString stringWithFormat:@"%@月", [self.selDate xd_MM]];
    }
    [self.timeBtn setTitle:dateStr forState:UIControlStateNormal];
    [self.timeBtn layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageRight imageTitlespace:8.0];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestCosplayListWithHeader:isHeader];
}

#pragma mark - network request
- (void)requestCosplayListWithHeader:(BOOL)isHeader {
    NSInteger startIndex = isHeader ? 0 : self.exhModel.exhibition_list.count;

    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(startIndex) forKey:@"index"];
    [pars setObject:@(kRequestExhibitionListSize) forKey:@"size"];
//    [pars setObject:@"" forKey:@"province"];
    if (self.selCity.length && ![self.selCity isEqualToString:@"全部"]) {
        [pars setObject:self.selCity forKey:@"city"];
    }
    if (self.selDate) {
        [pars setObject:[self.selDate xd_yyyy_MM] forKey:@"start_time"];
    }
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiExhibitionList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求展会列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] exhibitionListWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

- (KABExhibitionModel *)exhModel {
    return [KABModel sharedInstance].exhibitionList;
}

@end
